<template>
  <div class="container">
    <!-- 统计卡片模块 -->
    <div class="stats-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="stats-item total-card">
            <div class="card-content">
              <div class="card-title">
                <el-icon><Box /></el-icon>
                <span>总食材种类</span>
              </div>
              <div class="count-number blue-text">{{ totalItems }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="stats-item warning-card">
            <div class="card-content">
              <div class="card-title">
                <el-icon><Warning /></el-icon>
                <span>需补货食材</span>
              </div>
              <div class="count-number orange-text">{{ lowStockItems }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预警提示栏 -->
    <el-alert
      :title="`当前有${lowStockCount}种食材库存不足，请及时补充！`"
      type="warning"
      :closable="false"
      show-icon
      class="warning-bar"
      v-if="lowStockCount > 0"
    />

    <!-- 操作工具栏 -->
    <div class="control-bar">
      <div class="left">
        <el-input
          v-model="searchKey"
          placeholder="搜索食材名称"
          clearable
          style="width: 300px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="right">
        <el-button type="success" @click="openDialog('import')">
          <el-icon><Download /></el-icon>批量入库
        </el-button>
        <el-button type="primary" @click="openDialog('add')">
          <el-icon><Plus /></el-icon>新增食材
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="filteredInventory"
      border
      stripe
      style="width: 100%"
      height="calc(100vh - 340px)"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="食材名称" min-width="180" align="center" />
      <el-table-column label="当前库存" width="150" align="center">
        <template #default="{row}">
          <span :class="{'warning-text': row.quantity <= row.warningThreshold}">
            {{ row.quantity }} {{ row.unit }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="100" align="center" />
      <el-table-column label="预警阈值" width="150" align="center">
        <template #default="{row}">{{ row.warningThreshold }} {{ row.unit }}</template>
      </el-table-column>
      <el-table-column label="库存状态" width="120" align="center">
        <template #default="{row}">
          <el-tag :type="row.quantity > row.warningThreshold ? 'success' : 'danger'">
            {{ row.quantity > row.warningThreshold ? '正常' : '不足' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后更新" width="180" align="center">
        <template #default="{row}">{{ formatTime(row.updateTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="{row}">
          <el-button size="small" @click="openAdjustDialog(row)">调整库存</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 库存调整对话框 -->
    <el-dialog 
      v-model="adjustDialog.visible" 
      :title="`库存调整 - ${adjustDialog.currentItem?.name}`" 
      width="500px"
    >
      <el-form label-width="120px">
        <el-form-item label="调整类型" required>
          <el-radio-group v-model="adjustDialog.type">
            <el-radio label="in">入库</el-radio>
            <el-radio label="out">出库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" required>
          <el-input-number 
            v-model="adjustDialog.quantity"
            :min="1"
            controls-position="right"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="adjustDialog.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因或备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdjust">确认调整</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Box, Warning, Search, Download, Plus } from '@element-plus/icons-vue'

// 模拟库存数据
const inventoryData = ref([
  {
    id: 1,
    name: '牛排',
    quantity: 50,
    unit: 'kg',
    warningThreshold: 20,
    updateTime: '2023-11-22 09:30:00'
  },
  {
    id: 2,
    name: '龙虾',
    quantity: 30,
    unit: '只',
    warningThreshold: 10,
    updateTime: '2023-11-22 10:15:00'
  },
  {
    id: 3,
    name: '面粉',
    quantity: 200,
    unit: 'kg',
    warningThreshold: 50,
    updateTime: '2023-11-22 08:45:00'
  },
  {
    id: 4,
    name: '黄油',
    quantity: 15,
    unit: 'kg',
    warningThreshold: 20,
    updateTime: '2023-11-22 14:20:00'
  }
])

// 响应式数据
const loading = ref(false)
const searchKey = ref('')
const adjustDialog = reactive({
  visible: false,
  currentItem: null,
  type: 'in',
  quantity: 1,
  remark: ''
})

// 计算属性
const totalItems = computed(() => inventoryData.value.length)
const lowStockItems = computed(() => 
  inventoryData.value.filter(item => item.quantity <= item.warningThreshold).length
)
const lowStockCount = computed(() => lowStockItems.value)

const filteredInventory = computed(() => {
  return inventoryData.value
    .filter(item => item.name.toLowerCase().includes(searchKey.value.toLowerCase()))
    .sort((a, b) => a.quantity - b.quantity)
})

// 方法
const formatTime = (timeStr) => {
  return timeStr ? timeStr.slice(11, 16) : '--'
}

const handleSearch = () => {
  // 实际项目中可添加搜索逻辑
}

const resetSearch = () => {
  searchKey.value = ''
}

const openAdjustDialog = (item) => {
  adjustDialog.currentItem = item
  adjustDialog.visible = true
  adjustDialog.type = 'in'
  adjustDialog.quantity = 1
  adjustDialog.remark = ''
}

const confirmAdjust = () => {
  if (adjustDialog.type === 'in') {
    adjustDialog.currentItem.quantity += adjustDialog.quantity
  } else {
    if (adjustDialog.currentItem.quantity < adjustDialog.quantity) {
      ElMessage.error('库存不足无法出库')
      return
    }
    adjustDialog.currentItem.quantity -= adjustDialog.quantity
  }
  
  adjustDialog.currentItem.updateTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  ElMessage.success('库存调整成功')
  adjustDialog.visible = false
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该食材记录？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    inventoryData.value = inventoryData.value.filter(item => item.id !== id)
    ElMessage.success('删除成功')
  })
}

// 模拟菜品配方（需与订单管理联动）
const recipes = {
  '菲力牛排': { '牛排': 0.2, '黄油': 0.05 },
  '龙虾浓汤': { '龙虾': 1, '面粉': 0.1 },
  '意大利面': { '面粉': 0.3, '黄油': 0.02 }
}

// 模拟订单消耗（在订单完成时调用）
const consumeInventory = (dishName, quantity) => {
  if (recipes[dishName]) {
    Object.entries(recipes[dishName]).forEach(([ingredient, amount]) => {
      const item = inventoryData.value.find(i => i.name === ingredient)
      if (item) {
        item.quantity = Math.max(0, item.quantity - (amount * quantity))
        item.updateTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
      }
    })
  }
}

// 初始化模拟订单消耗（测试用）
onMounted(() => {
  // 模拟订单完成
  setTimeout(() => {
    consumeInventory('菲力牛排', 2)
    consumeInventory('意大利面', 3)
  }, 2000)
})
</script>

<style scoped>
.container {
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
  background: #f5f7fa;
}

/* 统计卡片样式 */
.stats-card {
  margin-bottom: 20px;
}

.stats-item {
  border-radius: 8px;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
}

.total-card {
  border-left: 4px solid #409eff;
}

.warning-card {
  border-left: 4px solid #e6a23c;
}

.card-content {
  padding: 20px;
  text-align: center;
}

.card-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #606266;
  font-size: 16px;
  
  .el-icon {
    font-size: 20px;
  }
}

.count-number {
  font-size: 32px;
  font-weight: 600;
}

.blue-text {
  color: #409eff;
}

.orange-text {
  color: #e6a23c;
}

.warning-bar {
  margin-bottom: 15px;
}

.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.warning-text {
  color: #e6a23c;
  font-weight: 600;
}

/* 表格样式 */
:deep(.el-table) {
  --el-table-border-color: #ebeef5;

  th.el-table__cell {
    background: #f8f9fa;
    font-weight: 600;
  }

  .el-table__row td {
    padding: 12px 0;
  }
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;

  .el-dialog__header {
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }
}
</style>